package com.cd.javacxy.module.web.controller;

import com.cd.javacxy.common.model.entity.SessionUser;
import com.cd.javacxy.common.model.enums.OrderByEnum;
import com.cd.javacxy.common.model.enums.ResponseCode;
import com.cd.javacxy.common.model.query.MessageQuery;
import com.cd.javacxy.common.model.vo.AjaxResponse;
import com.cd.javacxy.common.model.vo.CxyUserVo;
import com.cd.javacxy.common.model.vo.MessageVo;
import com.cd.javacxy.common.utils.Constants;
import com.cd.javacxy.common.utils.PageResult;
import com.cd.javacxy.module.base.BaseController;
import com.cd.javacxy.module.web.service.CxyMessageService;
import com.cd.javacxy.module.web.service.CxyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * CxyMessage的路由接口服务
 *
 * @author yanghy
 */
@Controller
@Slf4j
public class CxyMessageController extends BaseController {

    /**
     * CxyMessageService服务
     */
    private CxyMessageService cxyMessageService;

    private CxyUserService userService;

    @Autowired
    public void setCxyMessageService(CxyMessageService cxyMessageService) {
        this.cxyMessageService = cxyMessageService;
    }

    @Autowired
    public void setUserService(CxyUserService userService) {
        this.userService = userService;
    }

    @GetMapping("/message/list")
    public ModelAndView messageList(HttpSession session) {
        ModelAndView view = new ModelAndView("/page/admin/message_list");
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        if (sessionUser == null) {
            view.setViewName("redirect:" + Constants.LOGINABSOLUTEPATH);
            return view;
        }
        CxyUserVo user = this.userService.findUserInfo4UserHome(sessionUser.getUserId());
        if (user == null) {
            view.setViewName("redirect:" + Constants.ERROR_404);
            return view;
        }
        view.addObject("user", user);
        return view;
    }


    @GetMapping("/user/msg/list")
    @ResponseBody
    public AjaxResponse userMessageList(HttpSession session, MessageQuery messageQuery) {
        messageQuery.setReceivedUserId(this.getUserId(session));
        messageQuery.setOrderBy(OrderByEnum.MESSAGE_STATUS_ASC_CREATE_TIME_DESC);
        PageResult<MessageVo> result = this.cxyMessageService.findMessageByPage(messageQuery);
        return AjaxResponse.builder()
                .data(result)
                .code(ResponseCode.SUCCESS.getCode())
                .build();

    }

    @GetMapping("/user/msg/count")
    @ResponseBody
    public AjaxResponse<Object> userMsgCount(HttpSession session, MessageQuery messageQuery) {
        messageQuery.setReceivedUserId(this.getUserId(session));
        messageQuery.setOrderBy(OrderByEnum.MESSAGE_STATUS_ASC_CREATE_TIME_DESC);
        int count = this.cxyMessageService.findMessageCount(messageQuery);
        return AjaxResponse.builder()
                .data(count)
                .code(ResponseCode.SUCCESS.getCode())
                .build();
    }

    @ResponseBody
    @DeleteMapping("/del/msg")
    public AjaxResponse<Object> delMessage(HttpSession session, Integer[] ids) {
        this.cxyMessageService.delMessage(this.getUserId(session), ids);
        return AjaxResponse.builder().code(ResponseCode.SUCCESS.getCode()).build();
    }

    @PostMapping("/read/msg")
    @ResponseBody
    public ModelAndView readMessage(HttpSession session, Integer id) {
        ModelAndView view = new ModelAndView(Constants.ERROR_404);
        SessionUser sessionUser = (SessionUser) session.getAttribute(Constants.SESSION_USER_KEY);
        if (sessionUser == null) {
            view.setViewName("redirect:" + Constants.LOGINABSOLUTEPATH);
            return view;
        }
        try {
            CxyUserVo user = this.userService.findUserInfo4UserHome(sessionUser.getUserId());
            view.addObject("user", user);
            view.setViewName("redirect:" + this.cxyMessageService.getMessageById(id, this.getUserId(session)).getUrl());
            this.cxyMessageService.update(new Integer[]{id}, this.getUserId(session));
        } catch (Exception e) {
            log.error("获取消息列表失败：", e);
            view.setViewName("redirect:" + Constants.ERROR_404);
            return view;
        }
        return view;
    }

    @ResponseBody
    @PostMapping("/mark/msg/read")
    public AjaxResponse<Object> markMessageRead(HttpSession session, Integer[] ids) {
        int r = this.cxyMessageService.update(ids, this.getUserId(session));
        if (r > 0) {
            return AjaxResponse.builder()
                    .code(ResponseCode.SUCCESS.getCode())
                    .build();
        }
        return AjaxResponse.builder()
                .code(ResponseCode.BUSSINESSERROR.getCode())
                .errorMsg("标记已读出错,请重试")
                .build();
    }
}
